package com.jmb.api.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jmb.api.common.exception.WebApiException;
import com.jmb.api.common.result.ResultCodeEnum;
import com.jmb.api.entity.Permission;
import com.jmb.api.vo.permission.PermissionQueryVO;
import com.jmb.api.vo.permission.PermissionVO;
import com.jmb.api.web.service.PermissionService;
import com.jmb.api.web.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author 金梦博
* @description 针对表【t_permission】的数据库操作Service实现
* @createDate 2025-09-25 17:20:28
*/
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission>
    implements PermissionService{

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void saveOrUpdatePermission(Permission permission) {
        // 实现新增修改权限
        boolean isUpdate = permission.getId() != null;

        // 检查权限名称是否已存在
        LambdaQueryWrapper<Permission> permissionWrapper = new LambdaQueryWrapper<>();
        permissionWrapper.eq(Permission::getPermissionCode, permission.getPermissionCode());

        // 如果是修改操作，需要排除当前权限本身
        if (isUpdate){
            permissionWrapper.ne(Permission::getId, permission.getId());
        }
        // 查询是否存在相同权限名称
        Permission existingPermission = permissionMapper.selectOne(permissionWrapper);
        if (existingPermission != null){
            // 权限已存在，抛出异常
            throw new WebApiException(ResultCodeEnum.EXIST_ERROR);
        }
        // 新增父级权限的时候，默认设置一个0，表示没有父级权限
        Integer parentId = permission.getParentId();
        if (parentId == null){
            permission.setParentId(0);
        }
        // 执行保存或更新操作
        super.saveOrUpdate(permission);

    }

    /**
     * 删除权限
     * 删除父权限的时候，需要检查是否有子权限，如果有子权限，则不允许删除
     * @param id 传入的id
     */

    @Override
    public void deletePermission(Long id) {
        LambdaQueryWrapper<Permission> permissionWrapper = new LambdaQueryWrapper<>();
        permissionWrapper.eq(Permission::getParentId, id);
        if (permissionMapper.selectCount(permissionWrapper) > 0){
            // 存在子权限，不允许删除
            throw new WebApiException(ResultCodeEnum.DELETE_ERROR);
        }
        super.removeById(id);
    }

    @Override
    public IPage<PermissionVO> listPermission(IPage<PermissionVO> page, PermissionQueryVO permissionQueryVO) {
        return permissionMapper.listPermission(page, permissionQueryVO);
    }

    @Override
    public List<PermissionVO> listPermissionTree() {
        return permissionMapper.listPermissionTree();
    }
}




